﻿using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
using System.Collections;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using VOL.Core.DBManager;
using VOL.Core.Extensions;
using VOL.Core.ManageUser;
using VOL.Core.Services;
using VOL.Core.Utilities;
using VOL.Entity.DomainModels;
using syio = System.IO;

namespace VOL.Core.Utilities
{
    public class baiduAi_tools
    {
        // 调用getAccessToken()获取的 access_token建议根据expires_in 时间 设置缓存
        // 返回token示例
        //public static String TOKEN = "24.adda70c11b9786206253ddb70affdc46.2592000.1493524354.282335-1234567";

        // 百度云中开通对应服务应用的 API Key 建议开通应用的时候多选服务
        private static string clientId = "YfeBmcZZaqMT0oUxDfRAXqgd";
        // 百度云中开通对应服务应用的 Secret Key
        private static string clientSecret = "zzu5jQOyDZYL7dRSWlWQY9Cny9Depq3o";

        public static string getAccessToken()
        {
            string authHost = "https://aip.baidubce.com/oauth/2.0/token";
            HttpClient client = new HttpClient();
            List<KeyValuePair<string, string>> paraList = new List<KeyValuePair<string, string>>();
            paraList.Add(new KeyValuePair<string, string>("grant_type", "client_credentials"));
            paraList.Add(new KeyValuePair<string, string>("client_id", clientId));
            paraList.Add(new KeyValuePair<string, string>("client_secret", clientSecret));

            HttpResponseMessage response = client.PostAsync(authHost, new FormUrlEncodedContent(paraList)).Result;
            string result = response.Content.ReadAsStringAsync().Result;
            dynamic queryjson = JsonConvert.DeserializeObject(result);
            Console.WriteLine(queryjson.access_token);
            return queryjson.access_token;
        }

        public static string getFileBase64(string fileNamePath)
        {
            //string path = $"Upload/Tables/Fk_reim/202206081624018543/2019-5-4（300）.jpg";
            string fullPath = fileNamePath.MapPath(true);//VOL框架上传的文件，服务器读取方法

            FileStream filestream = new FileStream(fullPath, FileMode.Open);
            byte[] arr = new byte[filestream.Length];
            filestream.Read(arr, 0, (int)filestream.Length);
            string baser64 = Convert.ToBase64String(arr);
            filestream.Close();
            return baser64;
        }

        // 增值税发票识别
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static async Task<string> vatInvoice_async(string fileNamePath)
        {
            return await Task.Run(() =>
            {
                string token = getAccessToken();
                string host = "https://aip.baidubce.com/rest/2.0/ocr/v1/vat_invoice?access_token=" + token;
                Encoding encoding = Encoding.Default;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host);
                request.Method = "post";
                request.KeepAlive = true;
                // 图片的base64编码
                string base64 = getFileBase64(fileNamePath);
                String str = "image=" + HttpUtility.UrlEncode(base64);
                byte[] buffer = encoding.GetBytes(str);
                request.ContentLength = buffer.Length;
                request.GetRequestStream().Write(buffer, 0, buffer.Length);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default);
                string result = reader.ReadToEnd();
                Console.WriteLine("增值税发票识别:");
                //Console.WriteLine(result);
                return result;
            });
            
        }



        // OCR-增值税发票验真
        public static string invoiceVerification()
        {
            string token = getAccessToken();
            string host = "https://aip.baidubce.com/rest/2.0/ocr/v1/vat_invoice_verification?access_token=" + token;
            Encoding encoding = Encoding.Default;
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host);
            request.Method = "post";
            request.KeepAlive = true;
            string str = "invoice_code=" + "发票代码" + "&invoice_num=" + "发票号码" + "&invoice_date=" + "开票日期" + "&check_code=" + "校验码。填写发票校验码后6位" + "&invoice_type=" + "发票类型" + "&total_amount=" + "不含税金额";
            byte[] buffer = encoding.GetBytes(str);
            request.ContentLength = buffer.Length;
            request.GetRequestStream().Write(buffer, 0, buffer.Length);
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default);
            string result = reader.ReadToEnd();
            Console.WriteLine("OCR-增值税发票验真:");
            Console.WriteLine(result);
            return result;
        }
    }
}
